#include<iostream>
#include<unistd.h>
#include<pthread.h>

using namespace std;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int cnt = 0;

void *Rountine(void *args)
{
    pthread_detach(pthread_self());
    uint64_t number = (uint64_t)args;
    cout << "thread " << number << " created" << endl;
    while(true)
    {
        pthread_mutex_lock(&lock);
        //此处可加判断语句，不满足再在条件变量下等待
        pthread_cond_wait(&cond, &lock);
        cout << "thread " << number << " count, cnt = " << cnt++ << endl;
        pthread_mutex_unlock(&lock);
    }
}

int main()
{
    
    for(uint64_t i = 0; i < 4; ++i)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, Rountine, (void*)i);
        usleep(1000);
    }

    while(true)
    {
        sleep(2);
        pthread_cond_signal(&cond);
        cout << "main thread open one cond's" << endl;
        // pthread_cond_broadcast(&cond);
        // cout << "main thread open all cond's" << endl;
    }

    // pthread_mutex_destroy(&lock);
    // pthread_cond_destroy(&cond);

    return 0;
}